package cn.kmsoft.common;

import cn.kmsoft.common.exception.ServiceException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * 统一返回数据结构v1.0
 *
 * @author 北京捷泰天域-凌磊
 * @date 2017/11/1
 */
//@Data
//@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "接口返回信息")
public class RestResponse<T> {
    @ApiModelProperty(notes = "状态")
    private String status;

    @ApiModelProperty(notes = "消息")
    private String msg;

    @ApiModelProperty(notes = "状态码")
    private int code;

    @ApiModelProperty(notes = "返回的数据")
    private T result;

    @ApiModelProperty(notes = "时间戳")
    private Long timestamp;


    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public T getResult() {
        return result;
    }
    public void setResult(T result) {
        this.result = result;
    }

    public Long getTimestamp() {
        return timestamp;
    }
    public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
    }

    /**
     * 执行成功下的返回数据内容
     *
     * @param result
     * @param <T>
     * @return
     */
    public static <T> RestResponse succeed(T result) {
        RestResponse response = new RestResponse();

        response.setCode(200);
        response.setStatus(ResponseStatus.SUCCEED.getStatus());
        response.setResult(result);

        return response;
    }

    /**
     * 执行失败下的返回数据内容
     *
     * @param t
     * @return
     */
    public static RestResponse failed(Throwable t) {
        Throwable e = t.getCause() == null ? t : t.getCause();

        ServiceException serviceException = e instanceof ServiceException ? (ServiceException) e : new ServiceException();

        RestResponse response = new RestResponse();
        response.setCode(serviceException.getExceptionMsg().getCode());
        response.setStatus(ResponseStatus.FAILED.getStatus());
        response.setMsg(serviceException.getExceptionMsg().getMsg());
        response.setTimestamp(System.currentTimeMillis());

        return response;
    }
}
